from django.shortcuts import render
from django.views import View
from.models import Areas
from django import http
from django.core.cache import cache

# Create your views here.



class ProvinceAreasView(View):
    """获取省级地区数据"""

    def get(self,request):


        # 判断是否有缓存
        province_list = cache.get('province_list')

        if not province_list:
        # 获取省级地区数据
            try:
                provinces = Areas.objects.filter(parent_id__isnull=True)
            except Exception as e:
                return http.JsonResponse({'code':400, 'errmsg': '获取数据失败'})

            province_list = []

            for province in provinces:
                province_list.append({
                    'id': province.id,
                    'name': province.name
                })
            cache.set('province_list', province_list, 3600)

        return http.JsonResponse({'code':0,
                                  'errmsg': 'ok',
                                  'province_list': province_list})


class SubAreasView(View):
    """获取子级地区,市和区县"""

    def get(self,request,pk):

        sub_data = cache.get('sub_area' + pk)

        if not sub_data:

            # 获取省级级地区
            province = Areas.objects.get(pk=pk)

            # 获取该省级地区子级地区
            # sub_areas = province.subs.all()
            sub_areas = Areas.objects.filter(parent_id=pk)

            subs = []
            for sub_area in sub_areas:
                subs.append({
                    'id': sub_area.id,
                    'name': sub_area.name
                })

            sub_data = {
                'id': province.id,
                'name': province.name,
                'subs': subs
            }

            cache.set('sub_area' + pk, sub_data, 3600)

        # 返回数据
        return http.JsonResponse({'code': 0,
                                  'errmsg': 'ok',
                                  'sub_data': sub_data
                                  })
